package top.wineye.spring.dependency.inject;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import top.wineye.spring.dependency.pojo.BizHolder;

public class JavaApiDependencyInject {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext();

        // 读取 xml bean definition
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
        reader.loadBeanDefinitions("setter-inject-bean-factory-context.xml");


        // 通过 java api 创建 bean definition
        // setter 注入
        BeanDefinitionBuilder builder =
                BeanDefinitionBuilder.genericBeanDefinition(BizHolder.class);
        builder.addPropertyReference("biz", "biz");
        context.registerBeanDefinition("holder", builder.getBeanDefinition());

        // 通过 constructor 注入
        BeanDefinitionBuilder anotherBuilder =
                BeanDefinitionBuilder.genericBeanDefinition(BizHolder.class);
        anotherBuilder.addConstructorArgReference("biz");
        context.registerBeanDefinition("anotherHolder",
                anotherBuilder.getBeanDefinition());

        // refresh
        context.refresh();

        BizHolder bean = context.getBean("holder", BizHolder.class);
        System.out.println(bean);

        BizHolder anotherHolder = context.getBean("anotherHolder", BizHolder.class);
        System.out.println(anotherHolder);


        context.close();
    }
}
